package top.xiangqifu.fruit.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.xiangqifu.fruit.base.BasePageResult;
import top.xiangqifu.fruit.base.BaseResult;
import top.xiangqifu.fruit.dao.FruitDAO;
import top.xiangqifu.fruit.entity.PageBean;
import top.xiangqifu.fruit.entity.TbFruit;
import top.xiangqifu.fruit.service.FruitService;

import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class FruitServiceImpl implements FruitService {


    private FruitDAO fruitDAO;

    public FruitServiceImpl(FruitDAO fruitDAO) {
        this.fruitDAO = fruitDAO;
    }


    @Override
    public BaseResult add(TbFruit tbFruit){
        BaseResult result=new BaseResult<>();
        TbFruit tbFruit1=fruitDAO.queryName(tbFruit);
        if (tbFruit1!=null){
            result.setCode(500);
            result.setSuccess(false);
            result.setMessage("该成果名称已经存在，请重新输入");
            return result;
        }
        TbFruit  tbFruit2=new TbFruit();
        tbFruit2.setFruitName(tbFruit.getFruitName());
        tbFruit2.setAffiliationField(tbFruit.getAffiliationField());
        tbFruit2.setFruitInfo(tbFruit.getFruitInfo());
        tbFruit2.setEthics(tbFruit.getEthics());
        tbFruit2.setEffect(tbFruit.getEffect());
        tbFruit2.setAssess(tbFruit.getAssess());
        int i=fruitDAO.add(tbFruit2);
        return i==1?BaseResult.ok("添加成功"):BaseResult.fail("添加失败");
    }



    @Override
    public BaseResult delete(TbFruit tbFruit){
        int i = fruitDAO.delete(tbFruit);
        return i==1?BaseResult.ok("删除成功"):BaseResult.fail("删除失败");
    }


    @Override
    public BaseResult update(TbFruit tbFruit){
        TbFruit tbFruit1=new TbFruit();
        tbFruit1.setFruitName(tbFruit.getFruitName());
        tbFruit1.setAffiliationField(tbFruit.getAffiliationField());
        tbFruit1.setFruitInfo(tbFruit.getFruitInfo());
        tbFruit1.setEthics(tbFruit.getEthics());
        tbFruit1.setEffect(tbFruit.getEffect());
        tbFruit1.setAssess(tbFruit.getAssess());
        int i = fruitDAO.update(tbFruit);
        return i==1?BaseResult.ok("修改成功"):BaseResult.fail("修改失败");
    }


    @Override
    public BasePageResult<List<TbFruit>> query(TbFruit tbFruit, PageBean pageBean) {
        //分页处理
        pageBean = Optional.ofNullable(pageBean).orElse(new PageBean());
        //启动分页处理
        PageHelper.startPage(pageBean.getPageNumber(), pageBean.getPageSize());
        //回传分页信息
        List<TbFruit> list = fruitDAO.query(tbFruit);
        PageInfo<TbFruit> pageInfo = new PageInfo<TbFruit>(list);
        pageBean.setPageInfo(pageInfo);
        BasePageResult result = new BasePageResult();
        result.setSuccess(true);
        result.setCode(200);
        result.setMessage("");
        result.setPage(pageBean);
        result.setData(list);
        return result;
    }
}
